package servlet;

import DAO.CategoryDao;
import DAO.TelevisionDao;
import DAO.SubCategoryDao;
import DAO.SubcategoryTelevisionDao;
import bean.Category;
import bean.SubCategory;
import bean.Television;
import service.TelevisionService;
import service.CategoryService;
import service.SubCategoryService;
import service.impl.TelevisionServiceImpl;
import service.impl.CategoryServiceImpl;
import service.impl.SubCategoryServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@WebServlet("/television/*")
@MultipartConfig(
    fileSizeThreshold = 1024 * 1024, // 1 MB
    maxFileSize = 1024 * 1024 * 10,  // 10 MB
    maxRequestSize = 1024 * 1024 * 15 // 15 MB
)
public class TelevisionServlet extends HttpServlet {
    private TelevisionService televisionService;
    private CategoryService categoryService;
    private SubCategoryService subCategoryService;
    private SubcategoryTelevisionDao subcategoryTelevisionDao;

    @Override
    public void init() throws ServletException {
        TelevisionDao televisionDao = new TelevisionDao();
        SubCategoryDao subCategoryDao = new SubCategoryDao();
        this.televisionService = new TelevisionServiceImpl(televisionDao);
        this.categoryService = new CategoryServiceImpl(new CategoryDao());
        this.subCategoryService = new SubCategoryServiceImpl(subCategoryDao);
        this.subcategoryTelevisionDao = new SubcategoryTelevisionDao();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        if ("showAddForm".equals(action)) {
            showAddForm(request, response);
        } else if ("getSubCategories".equals(action)) {
            getSubCategories(request, response);
        } else if ("updateImage".equals(action)) {
            updateImage(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        if ("add".equals(action)) {
            addTelevision(request, response);
        } else if ("updateImage".equals(action)) {
            updateImage(request, response);
        }
    }

    private void showAddForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            List<Category> categories = categoryService.getAllCategories();
            request.setAttribute("categories", categories);
            
            Map<Integer, List<SubCategory>> categorySubcategories = new HashMap<>();
            for (Category category : categories) {
                List<SubCategory> subCategories = subCategoryService.getSubCategoriesByCategoryId(category.getId());
                categorySubcategories.put(category.getId(), subCategories);
            }
            request.setAttribute("categorySubcategories", categorySubcategories);
            
            request.getRequestDispatcher("/add_television.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "加载分类数据失败：" + e.getMessage());
            request.getRequestDispatcher("/add_television.jsp").forward(request, response);
        }
    }

    private void addTelevision(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取表单数据
            String name = request.getParameter("name");
            BigDecimal price = new BigDecimal(request.getParameter("price"));
            String screenSize = request.getParameter("screenSize");
            String resolution = request.getParameter("resolution");
            String model = request.getParameter("model");
            String description = request.getParameter("description");
            String[] subCategoryIds = request.getParameterValues("subCategoryId");

            // 处理图片上传
            Part filePart = request.getPart("image");
            String fileName = UUID.randomUUID().toString() + getFileExtension(filePart);
            String uploadPath = getServletContext().getRealPath("/static/img/电视机/");
            filePart.write(uploadPath + fileName);

            // 创建Television对象
            Television television = new Television();
            television.setName(name);
            television.setPrice(price);
            television.setScreenSize(screenSize);
            television.setResolution(resolution);
            television.setModel(model);
            television.setImageUrl(fileName);
            television.setDescription(description);

            // 保存电视机信息
            int televisionId = televisionService.addTelevision(television);

            // 保存分类关联
            if (subCategoryIds != null) {
                for (String subCategoryId : subCategoryIds) {
                    if (subCategoryId != null && !subCategoryId.isEmpty()) {
                        subcategoryTelevisionDao.addRelation(
                            Integer.parseInt(subCategoryId), 
                            televisionId
                        );
                    }
                }
            }

            // 重定向到商品列表页面
            response.sendRedirect(request.getContextPath() + "/category");

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "添加商品失败：" + e.getMessage());
            showAddForm(request, response);
        }
    }

    private String getFileExtension(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] tokens = contentDisp.split(";");
        for (String token : tokens) {
            if (token.trim().startsWith("filename")) {
                String fileName = token.substring(token.indexOf("=") + 2, token.length() - 1);
                return fileName.substring(fileName.lastIndexOf("."));
            }
        }
        return "";
    }

    private void getSubCategories(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String categoryId = request.getParameter("categoryId");
            List<SubCategory> subCategories = subCategoryService.getSubCategoriesByCategoryId(Integer.parseInt(categoryId));
            
            StringBuilder json = new StringBuilder("[");
            for (int i = 0; i < subCategories.size(); i++) {
                SubCategory sc = subCategories.get(i);
                json.append("{\"id\":").append(sc.getId())
                    .append(",\"name\":\"").append(sc.getName()).append("\"}");
                if (i < subCategories.size() - 1) {
                    json.append(",");
                }
            }
            json.append("]");
            
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(json.toString());
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("{\"error\":\"" + e.getMessage() + "\"}");
        }
    }

    public void updateImage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取电视机ID
            int televisionId = Integer.parseInt(request.getParameter("televisionId"));
            
            // 处理图片上传
            Part filePart = request.getPart("image");
            String fileName = UUID.randomUUID().toString() + getFileExtension(filePart);
            String uploadPath = getServletContext().getRealPath("/static/img/电视机/");
            
            // 获取原有电视机信息
            Television television = televisionService.getTelevisionById(televisionId);
            if (television != null && television.getImageUrl() != null) {
                // 删除原有图片
                File oldFile = new File(uploadPath + television.getImageUrl());
                if (oldFile.exists()) {
                    oldFile.delete();
                }
            }
            
            // 保存新图片
            filePart.write(uploadPath + fileName);
            
            // 更新数据库中的图片URL
            television.setImageUrl(fileName);
            televisionService.updateTelevision(television);
            
            // 返回成功响应
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write("{\"success\":true,\"imageUrl\":\"" + fileName + "\"}");
            
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("{\"success\":false,\"error\":\"" + e.getMessage() + "\"}");
        }
    }
} 